﻿using UnityEngine;
using UnityEngine.EventSystems;

public class FreeMoveJoystick : WorldJoystick, IPointerDownHandler, IPointerUpHandler, IDragHandler
{
    private readonly Vector2 _horMoveDir = new Vector2(60, 0);
    private readonly Vector2 _verMoveDir = new Vector2(0, 60);
    private Vector2 _lastKeyInputDir = Vector2.zero;

    void Update()
    {
        Vector2 keyInputDir = Vector2.zero;
        if (Input.GetKey(KeyCode.A))
        {
            keyInputDir += -_horMoveDir;
        }
        if (Input.GetKey(KeyCode.D))
        {
            keyInputDir += _horMoveDir;
        }
        if (Input.GetKey(KeyCode.W))
        {
            keyInputDir += _verMoveDir;
        }
        if (Input.GetKey(KeyCode.S))
        {
            keyInputDir += -_verMoveDir;
        }

        if (keyInputDir != Vector2.zero)
        {
            if (_lastKeyInputDir == Vector2.zero)
            {
                OnInputDown(Vector2.zero, keyInputDir);
            }
            else
            {
                OnInputDrag(Vector2.zero, keyInputDir);
            }
        }
        else
        {
            if (_lastKeyInputDir != Vector2.zero)
            {
                OnInputUp(Vector2.zero, _lastKeyInputDir);
            }
        }
        _lastKeyInputDir = keyInputDir;
        if(IsValidDrag)
        {
            InputModule.Instance.OnMoveJoystick(Displacement);
        }
    }


    #region Interface Implement
    public void OnPointerDown(PointerEventData eventData)
    {
        OnInputDown(eventData.pressPosition, eventData.position);

        float circleX = eventData.pressPosition.x / Screen.width * BaseTransform.rect.width * 2;
        float circleY = eventData.pressPosition.y / Screen.height * BaseTransform.rect.height;

        CircleTransform.anchoredPosition3D = new Vector3(circleX, circleY, 0);
        KnobTransform.anchoredPosition3D = new Vector3(0, 0, 0);
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        OnInputUp(eventData.pressPosition, eventData.position);
        CircleTransform.anchoredPosition3D = new Vector3(150, 150, 0);
        KnobTransform.anchoredPosition3D = new Vector3(0, 0, 0);
    }

    public void OnDrag(PointerEventData eventData)
    {
        OnInputDrag(eventData.pressPosition, eventData.position);
        KnobTransform.anchoredPosition3D = Vector2.ClampMagnitude(((eventData.position - eventData.pressPosition) / Screen.height * 750), 80);
    }
    #endregion
}
